package com.tools.convert;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class ConvertTools {
	
	public static Set<String> keySet = new HashSet<String>();
	
	public static Properties properties = new Properties();
	
	
	public ConvertTools(){
		load();
	}
	
	public void start(){
		createSWT();
	}
	
	private void createSWT(){
		JFrame frame = new JFrame("转换工具(版本V1.0)");
		Container container = frame.getContentPane();
		JTabbedPane tab = null;
		tab = new JTabbedPane(JTabbedPane.TOP);
		
		tab.addTab("文件转换", createPanel1());
		tab.addTab("属性设置", createPanel2());
		tab.addTab("查看日志", createPanel3());
		
		container.add(tab);
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(1);
			}
			
		});
		frame.setResizable(false);
		frame.setSize(900, 750);
		frame.setLocation(300, 200);
		frame.setVisible(true);
	}
	
	/**
	 * 初始化参数
	 */
	private void load(){
		Properties pro = new Properties();
		File file = null;
		/**创建该配置文件**/
		file = new File(System.getProperty("user.dir")+File.separator+"convert.properties");
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		try {
			pro.load(new FileInputStream(file));
			properties = pro;
			for(Entry<Object, Object> entry : pro.entrySet()){
				keySet.add(toStr(entry.getKey()));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void save(Properties pro){
		File file = null;
		file = new File(System.getProperty("user.dir")+File.separator+"convert.properties");
		try {
			pro.store(new FileOutputStream(file), "转换工具");
			load();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	private String convert(String[] dataArray){
		StringBuffer sb = new StringBuffer();
		if (dataArray != null && dataArray.length > 0) {
			for(String str : dataArray){
				str = str.trim();
				for(String s : keySet){
					if(str.startsWith(s)){
						str = str.replaceFirst(s, properties.getProperty(s));
						break;
					}
				}
				sb.append(str+"\n");
			}
		}
		return sb.toString();
	}
	
	/**
	 * 构造文件转换面板
	 * @return
	 */
	private JPanel createPanel1(){
		JPanel panel = new JPanel();
		
		final JTextArea area1 = new JTextArea(800, 400);
		final JTextArea area2 = new JTextArea(800, 400);
		
		JButton button = new JButton("开始转换");
		JButton button2 = new JButton("替换");
		JLabel label = new JLabel("请输入需要转换的文件名");
		JLabel label2 = new JLabel("替换");
		JLabel label3 = new JLabel();
		label3.setText("为");
		final JTextField field1 = new JTextField();
		final JTextField field2 = new JTextField();
		label2.setBounds(370, 18, 30, 22);
		label3.setBounds(560, 18, 30, 22);
		field1.setBounds(400, 18, 150, 22);
		field2.setBounds(580, 18, 150, 22);
		button2.setBounds(740, 18, 60, 22);
		
		panel.setLayout(null);
		
		Font x = new Font("Serif", 0, 16);
		area1.setFont(x);
		area2.setFont(x);
		
		area1.setLineWrap(true);
		area1.setEditable(true);
		
		area2.setLineWrap(true);
		area2.setEditable(true);
		
		label.setBounds(10, 20, 200, 20);
		
		button.setBounds(10, 340, 100, 30);
		
		button2.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				String text = area1.getText();
				String replace1 = field1.getText();
				String replace2 = field2.getText();
				text = text.replaceAll(replace1, replace2);
				area1.setText(text);
			}
			
		});
		
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				try {
					String text = area1.getText();
					if(text != ""){
						String[] array = null;
						array = text.split("\n");
						String result = convert(array);
						area2.setText(result);
						log(result);
						showLog();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		area1.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
		area2.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
		
		JScrollPane scrollArea1 = new JScrollPane(area1,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		
		JScrollPane scrollArea2 = new JScrollPane(area2,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		
		scrollArea1.setSize(200, 200);
		scrollArea1.setBounds(10, 50, 850, 280);
		
		scrollArea2.setSize(200, 200);
		scrollArea2.setBounds(10, 380, 850, 270);
		
		panel.setLayout(null);
		panel.add(label);
		panel.add(scrollArea1);
		panel.add(scrollArea2);
		panel.add(button);
		panel.add(field1);
		panel.add(field2);
		panel.add(label2);
		panel.add(label3);
		panel.add(button2);
		return panel;
	}
	
	
	private JPanel createPanel2(){
		JPanel panel = new JPanel();
		panel.setLayout(null);
		JButton addRowBtn = new JButton("增加行");
		JButton removeRowBtn = new JButton("删除行");
		JButton saveBtn = new JButton("保存");
		
		String[] title = {"原文件名", "替换后的内容"};
		Object[][] info = new Object[][]{};
		
		final DefaultTableModel tableModel = new DefaultTableModel(info, title);
		for(Entry<Object, Object> entry : properties.entrySet()){
			tableModel.addRow(new Object[]{entry.getKey(), entry.getValue()});
		}
		addRowBtn.setBounds(250, 10, 100, 20);
		removeRowBtn.setBounds(390, 10, 100, 20);
		saveBtn.setBounds(650, 660, 100, 20);
		final JTable table = new JTable(tableModel);
		
		panel.add(addRowBtn);
		panel.add(removeRowBtn);
		panel.add(saveBtn);
		
		addRowBtn.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent event) {
				tableModel.addRow(new Object[]{});
			}
		});
		
		removeRowBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int row = table.getSelectedRow();
				if(row != -1){
					tableModel.removeRow(row);
				}
			}
		});
		
		saveBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				int rowCount = tableModel.getRowCount();
				Properties pro = new Properties();
				for(int i=0; i<rowCount; i++){
					String data1 = toStr(tableModel.getValueAt(i, 0));
					String data2 = toStr(tableModel.getValueAt(i, 1));
					int row=table.getSelectedRow();
					int col=table.getSelectedColumn();
					table.getCellEditor(row,col).stopCellEditing();
					if(data1.length() > 0 && data2.length() > 0){
						pro.setProperty(data1, data2);
					}
				}
				System.out.println(pro);
				save(pro);
			}
		});
		
		Font font = new Font("Serif", 0, 16);
		table.setFont(font);
		table.setRowHeight(20);
		JScrollPane scroll = new JScrollPane(table);
		scroll.setBounds(10, 50, 400, 400);
		
		scroll.setSize(760, 600);
		panel.add(scroll);
		return panel;
	}
	
	private JPanel createPanel3(){
		JPanel panel = new JPanel();
		panel.setLayout(null);
		final JTextArea area = new JTextArea(800, 400);
		area.setEditable(false);
		JScrollPane scrollArea1 = new JScrollPane(area,
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		scrollArea1.setBounds(10, 20, 880, 650);
		String logs = showLog();
		area.setText(logs);
		panel.add(scrollArea1);
		return panel;
	} 
	
	private void log(String content){
		File file = null;
		file = new File(System.getProperty("user.dir")+File.separator+"convert.log");
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		 FileWriter fw;
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String now = format.format(new Date());
			fw = new FileWriter(file, true);
			fw.write(content);
			fw.write(now+"\n");
			fw.write("\n\n");
			fw.flush();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	
	private String showLog(){
		File file = new File(System.getProperty("user.dir")+File.separator+"convert.log");
		StringBuffer sb = new StringBuffer();
		if (file.exists()) {
			try {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), "GBK");
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTXT = null;
				List<String> list = new ArrayList<String>();
				while ((lineTXT = bufferedReader.readLine()) != null) {
					list.add(lineTXT.toString().trim()+"\n");
				}
				for(int i=list.size()-1; i>0; i--){
					sb.append(list.get(i));
				}
				bufferedReader.close();
				read.close();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	
	private String toStr(Object str){
		if(str == null){
			return "";
		}
		return String.valueOf(str).trim();
	}
	
	public static void main(String[] args) {
		ConvertTools tools = new ConvertTools();
		tools.start();
	}
}
